/*
 * PreferencesPanel.java
 *
 * Created on 27 juin 2010, 09:06:51
 */
package darknet.gui.core;

import darknet.DarknetUtilities;
import darknet.PublicInformation;
import darknet.core.impl.friend.FriendImpl;
import darknet.core.impl.net.NodeImpl;
import darknet.core.spec.Facade;
import darknet.core.spec.exception.ImportingMyselfException;
import darknet.core.spec.friend.Friend;
import darknet.core.spec.net.Node;
import darknet.core.spec.net.NodeState;
import java.awt.Color;
import java.io.File;
import java.io.IOException;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author Yoyo
 */
public class PreferencesPanel extends javax.swing.JPanel {

    /** Application's Facade. */
    private Facade facade;

    /** Creates new form PreferencesPanel */
    public PreferencesPanel(Facade facade) {

        if (facade == null) {
            throw new IllegalArgumentException("facade is null");
        }
        this.facade = facade;

        initComponents();

        loadFriendList();
        labelFeedback.setText("");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listFriends = new javax.swing.JList();
        btnAdd = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        btnExport = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jEditorPane1 = new javax.swing.JEditorPane();
        labelFeedback = new javax.swing.JLabel();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Friends"));

        listFriends.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(listFriends);

        btnAdd.setText("+");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnDelete.setText("-");
        btnDelete.setMaximumSize(new java.awt.Dimension(25, 25));
        btnDelete.setMinimumSize(new java.awt.Dimension(25, 25));
        btnDelete.setPreferredSize(new java.awt.Dimension(25, 25));
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        btnExport.setText("Export My Node");
        btnExport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExportActionPerformed(evt);
            }
        });

        jEditorPane1.setContentType("text/html");
        jEditorPane1.setEditable(false);
        jEditorPane1.setText("<html>\r\n  <head>\r\n  </head>\r\n  <body>\r\n<h3>Edit your friends list</h3>\n<p>\nHere, you can manage your list of friends.<br />\n<br />\nClick on the \"+\" button to add a friend.<br/>\nYour friend must send to you informations about him. Typically, he send to you a single file containing all informations about him.<br />\n<br />\nThe \"-\" button delete a friend of your list. This ex-friend will not be able to communicate with you.<br />\n<br />\n\"Export My Node\" generate a single file containing all your informations (pseudo, certificate, ip address and port). You must export this file to your friend fo be able to communicate together.\n</p>\n  </body>\r\n</html>\r\n");
        jScrollPane2.setViewportView(jEditorPane1);

        labelFeedback.setText("[feedback]");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnDelete, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnExport, javax.swing.GroupLayout.DEFAULT_SIZE, 154, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 252, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 508, Short.MAX_VALUE)
                    .addComponent(labelFeedback, javax.swing.GroupLayout.DEFAULT_SIZE, 508, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 366, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 366, Short.MAX_VALUE))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(labelFeedback, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(6, 6, 6)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnExport, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(btnDelete, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE)))))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(35, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void loadFriendList() {
        
        DefaultListModel list = new DefaultListModel();
        for(String friendName : facade.getFriendManager().get()) {
            list.addElement(friendName);
        }
        listFriends.setModel(list);
        
    }

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed


       

        new javax.swing.SwingWorker<Object, Object>() {

            @Override
            protected Object doInBackground() {

                Facade facade = PreferencesPanel.this.facade;
                JLabel labelFeedback = PreferencesPanel.this.labelFeedback;

                JFileChooser chooser = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter(
                        "Node infos *nodeinfo", "nodeinfo");
                chooser.setFileFilter(filter);
                int result = chooser.showOpenDialog(PreferencesPanel.this);

                if (result != JFileChooser.APPROVE_OPTION) {
                    return null;
                }

                File infoFile = chooser.getSelectedFile();
                PublicInformation info = null;
                try {
                    info = PublicInformation.restaure(infoFile);
                } catch (IOException ex) {
                    labelFeedback.setForeground(Color.RED);
                    labelFeedback.setText(
                            "Error while importing information : " + ex);
                    return null;
                }

                try {
                    facade.getFriendManager().add(
                        new FriendImpl(info.getPseudo(),
                        info.getCertificate()));

                } catch (ImportingMyselfException ex) {

                    labelFeedback.setForeground(Color.RED);
                    labelFeedback.setText("You can't add yourself");
                    return null;

                } catch (IOException ex) {

                    labelFeedback.setForeground(Color.RED);
                    labelFeedback.setText("Error while adding a friend : "
                            + ex.getLocalizedMessage());
                    return null;
                }


                facade.getNetworkManager().update(
                        new NodeImpl(info.getPseudo(), info.getAddress(),
                        info.getPort(), NodeState.OFFLINE));

                labelFeedback.setForeground(Color.GREEN);
                labelFeedback.setText("File successfully imported");

                loadFriendList();

                return null;
            }
        }.execute();


    }//GEN-LAST:event_btnAddActionPerformed

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed


       

        new javax.swing.SwingWorker<Object, Object>() {

            @Override
            protected Object doInBackground() {

                JLabel labelFeedback = PreferencesPanel.this.labelFeedback;
                JList listFriends = PreferencesPanel.this.listFriends;

                String nodeName = (String) listFriends.getSelectedValue();

                try {
                    facade.getFriendManager().remove(nodeName);
                    PreferencesPanel.this.loadFriendList();

                } catch (IOException ex) {
                    labelFeedback.setForeground(Color.RED);
                    labelFeedback.setText("Error while removing a friend : "
                            + ex.getLocalizedMessage());
                    return null;
                }

                labelFeedback.setForeground(Color.GREEN);
                labelFeedback.setText("Node friend successfully delete");

                return null;
            }

        }.execute();
        
    }//GEN-LAST:event_btnDeleteActionPerformed

    private void btnExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExportActionPerformed

        new javax.swing.SwingWorker<Object, Object>() {

            @Override
            protected Object doInBackground() {

                Facade facade = PreferencesPanel.this.facade;
                JLabel labelFeedback = PreferencesPanel.this.labelFeedback;

                Node myNode = facade.getNetworkManager().myNode();
                Friend myself = facade.getFriendManager().getMe();

                JFileChooser chooser = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter(
                        "Node infos *nodeinfo", "nodeinfo");
                chooser.setFileFilter(filter);
                int result = chooser.showSaveDialog(PreferencesPanel.this);
                if (result != JFileChooser.APPROVE_OPTION) {
                    return null;
                }

                labelFeedback.setForeground(Color.GREEN);
                labelFeedback.setText("Exporting file...");
                File myInformationsFile = chooser.getSelectedFile();
                myInformationsFile = new File(myInformationsFile.getAbsolutePath() + ".nodeinfo");
                try {
                    DarknetUtilities.exportMyInformations(myNode, myself,
                            myInformationsFile);
                } catch (IOException ex) {
                    labelFeedback.setForeground(Color.RED);
                    labelFeedback.setText("Error while exporting information :"
                            + ex.getLocalizedMessage());
                    return null;
                }

                labelFeedback.setForeground(Color.GREEN);
                labelFeedback.setText("File successfully exported");
                return null;
            }
        }.execute();

    }//GEN-LAST:event_btnExportActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnExport;
    private javax.swing.JEditorPane jEditorPane1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel labelFeedback;
    private javax.swing.JList listFriends;
    // End of variables declaration//GEN-END:variables
}
